var warehouse =require('./warehouse_merchants.js')
var mongoose=require('mongoose')
//连接数据库
var db=mongoose.createConnection('mongodb://127.0.0.1:27017/users')
//定义模型 规定数据类型 key 与表(集合) 必须一致
var newScheam=mongoose.Schema({
	name:String,
	password:String,
	_id:String,
	HeadImg:String
})
//关联表(集合) 
var mode=db.model('merchants',newScheam)

class operation {
	constructor(arg) {
	    this.warehouse=warehouse
	};
	//新添用户
	append(obj){
		return new Promise((resolve,reject)=>{
			var StoreName=obj.StoreName||null;//店铺名
			var name=obj.name||null;//用户名
			var HeadImg=obj.HeadImg;
			var password=obj.password||null;
			var _id=obj._id||null
			new mode({
				_id,
				name,
				password,
				HeadImg,
			}).save().then(
			 result=>{
				 warehouse.append({_id,StoreName}).then(
					result=>{
						console.log(result)
					},
					err=>{
						console.log(err)
					}
				 )
				 resolve('商家用户添加成功')
			 },
			 err=>{
				 resolve('商家用户添加失败',err)
			 }
			)
		});
	};
	//查询账户密码
	query(obj){
		var name=obj.name;
		var password=obj.password;
		return new Promise((resolve,reject)=>{
			mode.find({name,password},(err,doc)=>{
				if(err||!doc[0]){
					resolve(null)
					return;
				}
				resolve(doc[0])
			})
		})
	};
	queryInfo(ID){
		return new Promise((resolve,reject)=>{
			mode.find({'_id':ID},(err,doc)=>{
				if(err||!doc[0]){
					resolve(null)
					return;
				}
				resolve(doc[0])
			})
		})
	}
	//查询用户是否存在
	hasUser(obj){
		var name=obj.name;
		return new Promise((resolve,reject)=>{
			mode.find({name},(err,doc)=>{
				if(err||!doc[0]){
					resolve(null)
					return;
				}
				resolve(doc[0])
			})
		})
	};
	//查询所有商家用户
	findAll(){
		return new Promise((resolve,reject)=>{
			mode.find({},(err,doc)=>{
				if(err||!doc[0]){
					reject('错误',err)
					return;
				}
				resolve(doc)
			})
		})
	}
	//更行修改数据
	upDate(query,parms){
		return new Promise((resolve,reject)=>{
			if(parms._id){
				reject('不能修改_id')
			}
			mode.updateOne(query,parms,(err,doc)=>{
				if(err){
					console.log('错误')
						reject(err)
						return;
					}
					console.log(query,parms,doc);
					resolve(doc)
			})
		})
	}
}
module.exports= new operation()